package com.justreading.netty.http;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.*;
import io.netty.util.CharsetUtil;

import java.net.URL;

/**
 * @author LYJ
 * @Description
 * @date 2021 年 10 月 28 日 下午8:04
 */

/*
说明
1.    SimpleChannelInboundHandler 是 ChannelInboundHandlerAdapter
2.    HttpObject 客户端和服务器端相互通讯的数据被封装成 HttpObject
*/
public class TestHttpServerHandler extends SimpleChannelInboundHandler<HttpObject> {

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception {
        System.out.println(ctx.pipeline().channel().eventLoop().hashCode());
        if (msg instanceof HttpRequest) {
            System.out.println("pipleLine hashCode" + ctx.pipeline().hashCode() + "TestHttpServerHandler hash = " + this.hashCode());
            System.out.println("msg类型 = " + msg.getClass());
            System.out.println("客户端地址" + ctx.channel().remoteAddress());
        }
//        assert msg instanceof HttpRequest;
        HttpRequest httpRequest = (HttpRequest) msg;

        //不使用这个URL的类
//        URL url = new URL(httpRequest.uri());
        if ("/favicon.ico".equals(httpRequest.uri())) {
            System.out.println("请求favicon.icon,不做响应");
            return;
        }

        //回复信息给浏览器 [http 协议]
        ByteBuf content = Unpooled.copiedBuffer("hello我是服务器", CharsetUtil.UTF_8);

        //构造一个 http 的相应,即 httpresponse
        FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, content);

        response.headers().set(HttpHeaderNames.CONTENT_TYPE,"text/plain");
        response.headers().set(HttpHeaderNames.CONTENT_LENGTH,content.readableBytes());

        //返回响应
        ctx.writeAndFlush(response);
    }

    //但是还是有问题
    //客户端提前关闭造成的
//    An exceptionCaught() event was fired, and it reached at the tail of the pipeline. It usually means the last handler in the pipeline did not handle the exception.
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        super.exceptionCaught(ctx, cause);
        Channel channel = ctx.channel();
        if(channel.isActive()) ctx.close();
    }
}
